<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Http\Controllers\LayuiController as Layui;
use App\Http\Controllers\Admin\DateController;
use App\Models\UserAccount;
use App\Models\Order;
use App\Models\UserAddress;
use App\Models\UserInvite;
use App\Models\AccountLog;
use App\Models\UserLevel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use App\Jobs\ExportData;
use Illuminate\Support\Facades\Storage;
use App\Exceptions\FormException;
use App\Services\DreamBoxService;

class UserController extends Controller
{

    private $box_service;

    public function __construct()
    {
        $this->box_service = new DreamBoxService();
    }


    /**
     * 列表页面
     *
     * @Author   qizhifei
     * @DateTime 2019-05-29
     * @return   [type]     [description]
     */
    public function index()
    {
        return view('Admin.user.index');
    }

    /**
     * 获取数据
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function table(Request $request)
    {
        $payload = $request->all();
        //关联模型查询
        $preData = User::with(['userAccountInfo', 'userDepartment', 'userHasOrder' => function ($query) {
            //给模型里面添加搜索条件
            $query->Where('status', Order::STATUS_SUCCESS);
        }])
            ->when((isset($payload['level']) && $payload['level'] != ''), function ($query) use ($payload) {
                $query->whereHas('userAccountInfo', function ($query) use ($payload) {
                    $query->Where('user_level_id', $payload['level']);
                });
            })
            ->where(function ($query) use ($payload) {
                if (isset($payload['name']) && $payload['name'] != '') {
                    $query->Where('realname', 'like', "%$payload[name]%")
                        ->orWhere('phone', 'like', "%$payload[name]%")
                        ->orWhere('number', 'like', "%$payload[name]%");
                }
                if (isset($payload['datetime']) && $payload['datetime'] != '') {
                    $datetime = explode(' ~ ', $payload['datetime']);
                    try {
                        $starttime = Carbon::parse($datetime[0] ?? '')->toDateTimeString();
                        $endtime = Carbon::parse($datetime[1] ?? '')->toDateTimeString();
                    } catch (\Exception $exception) {
                        throw new FormException('请选择有效查询范围');
                    }
                    $query->whereBetween('created_at', [$starttime, $endtime]);
                }

                if (isset($payload['user_type']) && $payload['user_type'] != '') {
                    $query->Where(['user_type' => $payload['user_type']]);
                }
            })
            ->orderBy('id', 'desc')
            ->paginate($request->get('limit', 10));

        $data = $preData->map(function ($item) {
            $item->surplus_time = $this->surplusTime($item->userAccountInfo); //会员剩余时间
            $item->calcLevel = is_null($item->userAccountInfo) ? '' : $this->calcLevel($item->userAccountInfo); //会员等级
            $item->user_type_name = is_null($item->user_type) ? '' : ($item->user_type == 1 ? '员工' : '用户'); //会员身份
            $item->sex_name = is_null($item->sex) ? '' : ($item->sex == 1 ? '男' : '女'); //性别
//            $coin_consh = $this->box_service->coin_consh($item->openid); //获取贝壳以及八贝币
            $item->money_consh = isset($coin_consh['ke']) ? round($coin_consh['ke'], 2) : 0 ; //贝壳余额
            $item->money_eight_consh = isset($coin_consh['bi']) ? round($coin_consh['bi'], 2) : 0; //八贝币余额
            $item->money_recharge = is_null($item->userAccountInfo) ? '' : round($item->userAccountInfo->money_recharge, 2);
            $userHasOrder = $item->userHasOrder;
            $item->order_num = collect($userHasOrder)->count();
            $item->total_real_pay = is_null($userHasOrder) ? 0 : collect($userHasOrder)->sum('real_pay');
            $item->inviteInfo = $this->inviteInfo($item->inviter_user_id);
            return $item;
        });

        return Layui::tableJson($preData, 0, $preData->total());
    }

    /**
     * 获取邀请人信息
     *
     * @Author   qizhifei
     * @DateTime 2019-05-29
     * @param    [type]     $id [description]
     * @return   [type]         [description]
     */
    public function inviteInfo($id)
    {
        if (is_null($id)) {
            return '';
        } else {
            return User::with(['userDepartment'])
                ->where(['id' => $id])
                ->first();
        }


    }

    /**
     * 计算剩余会员时间
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    [type]     $userAccountInfo [description]
     * @return   [type]                      [description]
     */
    public function surplusTime($userAccountInfo)
    {
        if (is_null($userAccountInfo) || $userAccountInfo->user_level_id == 1) {
            return '';
        } else {
            $surplusTime = DateController::span($userAccountInfo->time_level, time(), 'days,hours,minutes,seconds');
            if ($surplusTime['days'] > 0) {
                return '剩余' . $surplusTime['days'] . '天';
            } elseif ($surplusTime['hours'] > 0) {
                return '剩余' . $surplusTime['hours'] . '小时';
            } elseif ($surplusTime['minutes'] > 0) {
                return '剩余' . $surplusTime['minutes'] . '分钟';
            } elseif ($surplusTime['seconds'] > 0) {
                return '剩余' . $surplusTime['seconds'] . '秒';
            }
        }
    }


    /**
     * 拼接会员等级
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    [type]     $userAccountInfo [description]
     * @return   [type]                      [description]
     */
    public function calcLevel($userAccountInfo)
    {
        if (is_null($userAccountInfo) || is_null($userAccountInfo->user_level_id)) {
            return '';
        } else {
            $userLevel = $userAccountInfo->user_level_id;
            return UserAccount::LEVEL[$userLevel];
        }
    }


    /**
     * 查看详情
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    [type]     $id [description]
     * @return   [type]         [description]
     */
    public function show($id)
    {

        $preData = User::with(['userAccountInfo', 'userHasOrder' => function ($query) {
            //$query->Where('status',Order::STATUS_SUCCESS);
            $query->orderBy('id', 'desc');
        }, 'provinceInfo', 'cityInfo'])
            //->withCount('userHasInvite')
            ->where('id', $id)
            ->first();

        //查出邀请人 当前会员的父级
        //$registerUser = UserInvite::where(['register_user_id'=>$id])->first();
        if ($preData->inviter_user_id != 0) {
            $inviteData = User::with(['userDepartment'])
                ->where('id', $preData->inviter_user_id)
                ->first();
        } else {
            $inviteData = '';
        }



        $preData->user_has_invite_count = User::where(['inviter_user_id'=>$id,'is_real'=>1])->count();
        $preData->surplus_time = $this->surplusTime($preData->userAccountInfo); //会员剩余时间
        $preData->calcLevel = is_null($preData->userAccountInfo) ? '' : $this->calcLevel($preData->userAccountInfo); //会员等级
        //$preData->user_type_name = is_null($preData->user_type) ? '' : ( $preData->user_type == 1 ? '员工' : '用户' ); //会员身份
        //$preData->department_name = is_null($preData->userDepartment) ? '' : $preData->userDepartment->department_name;
        $preData->sex_name = is_null($preData->sex) ? '' : ($preData->sex == 1 ? '男' : '女'); //性别

        $coin_consh = $this->box_service->coin_consh($preData->openid); //获取贝壳以及八贝币
        $preData->money_consh = $coin_consh['ke'] ? round($coin_consh['ke'], 2) : 0 ; //贝壳余额
        $preData->money_eight_consh = $coin_consh['bi'] ? round($coin_consh['bi'], 2) : 0; //八贝币余额
        $preData->money_recharge = is_null($preData->userAccountInfo) ? 0 : round($preData->userAccountInfo->money_recharge, 2);//充值余额
        $userHasOrder = $preData->userHasOrder; //关联订单
        $preData->order_num = collect($userHasOrder)->count(); //订单数


        //计算订单金额
        $realPay = Order::where(['status'=>Order::STATUS_SUCCESS , 'user_id'=>$id])->sum('real_pay');
        $preData->total_real_pay = empty($realPay) ? 0 : round($realPay,2); //交易额

        return view('Admin.user.show', ['data' => $preData, 'inviteData' => $inviteData]);
    }

    /**
     * 导出数据
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function export(Request $request)
    {
        $payload = $request->all();
        $filename = $request->input('filename', 'demo.csv');
        $filename = rtrim($filename, '.csv') . '.csv';

        if (Storage::disk('exports')->exists($filename))
            return $this->getResponse('文件已存在，请重新输入', [], 302, url('admin/user/index'));
        //判断前台是否有选择
        if (empty($payload['ids'])) {
            /* 获取查询条件 */
            $preData = User::with(['userAccountInfo', 'userDepartment', 'userHasOrder' => function ($query) {
                $query->Where('status', Order::STATUS_SUCCESS);
            }])
                ->when((isset($payload['level']) && $payload['level'] != ''), function ($query) use ($payload) {
                    $query->whereHas('userAccountInfo', function ($query) use ($payload) {
                        $query->Where('user_level_id', $payload['level']);
                    });
                })
                ->where(function ($query) use ($payload) {
                    if (isset($payload['name']) && $payload['name'] != '') {
                        $query->Where('realname', 'like', "%$payload[name]%")
                            ->orWhere('phone', 'like', "%$payload[name]%")
                            ->orWhere('number', 'like', "%$payload[name]%");
                    }
                    if (isset($payload['datetime']) && $payload['datetime'] != '') {
                        $datetime = explode(' ~ ', $payload['datetime']);
                        try {
                            $starttime = Carbon::parse($datetime[0] ?? '')->toDateTimeString();
                            $endtime = Carbon::parse($datetime[1] ?? '')->toDateTimeString();
                        } catch (\Exception $exception) {
                            throw new FormException('请选择有效查询范围');
                        }
                        $query->whereBetween('created_at', [$starttime, $endtime]);
                    }
                    if (isset($payload['user_type']) && $payload['user_type'] != '') {
                        $query->Where(['user_type' => $payload['user_type']]);
                    }
                })
                ->orderBy('id', 'desc')
                ->get();
        } else {
            //有选择
            $ids = explode(',', $payload['ids']);
            $preData = User::with(['userAccountInfo', 'userDepartment', 'userHasOrder' => function ($query) {
                $query->Where('status', Order::STATUS_SUCCESS);
            }])
                ->whereIn('id', $ids)
                ->orderBy('id', 'desc')
                ->get();
        };

        //整理数据
        $data = $preData->map(function ($item) {
            $item->surplus_time = $this->surplusTime($item->userAccountInfo); //会员剩余时间
            $item->calcLevel = is_null($item->userAccountInfo) ? '' : $this->calcLevel($item->userAccountInfo); //会员等级
            $item->user_type_name = is_null($item->user_type) ? '' : ($item->user_type == 1 ? '员工' : '用户'); //会员身份
            $item->sex_name = is_null($item->sex) ? '' : ($item->sex == 1 ? '男' : '女'); //性别
            //$item->department_name = is_null($item->userDepartment) ? '' : $item->userDepartment->department_name;
            $coin_consh = $this->box_service->coin_consh($item->openid); //获取贝壳以及八贝币
            $item->money_consh = $coin_consh['ke'] ? round($coin_consh['ke'], 2) : 0 ; //贝壳余额
            $item->money_eight_consh = $coin_consh['bi'] ? round($coin_consh['bi'], 2) : 0; //八贝币余额
            $item->money_recharge = is_null($item->userAccountInfo) ? '' : round($item->userAccountInfo->money_recharge, 2);

            $userHasOrder = $item->userHasOrder;
            $item->order_num = collect($userHasOrder)->count();
            $item->total_real_pay = is_null($userHasOrder) ? 0 : collect($userHasOrder)->sum('real_pay');

            $inviteUser = $this->inviteInfo($item->inviter_user_id);
            $item->invite_realname = is_null($inviteUser) ? '' : $inviteUser->realname;
            $item->invite_number = is_null($inviteUser) ? '' : $inviteUser->number;
            $item->invite_department_name = is_null($inviteUser) ? '' : (is_null($inviteUser->user_department) ? '' : $inviteUser->user_department->department_name);
            return $item;
        });


        if (count($data) == 0) {
            return $this->getResponse('导出不能为空，请重新尝试', [], 302, url('admin/user/index'));
        }

        /* 定义文件头 */
        $header = [
            'id' => '序号',
            'nickname' => '微信昵称',
            'phone' => '手机号码',
            'sex_name' => '性别',
            'created_at' => '注册时间',
            'calcLevel' => '会员等级',
            'surplus_time' => '剩余时间',
            'user_type_name' => '会员身份',
            'invite_realname' => '所属员工名字',
            'invite_number' => '所属员工编号',
            'invite_department_name' => '所属员工部门',
            'money_consh' => '贝壳余额',
            'money_eight_consh' => '八贝币余额',
            'money_recharge' => '充值余额',
            'order_num' => '总订单数',
            'total_real_pay' => '总金额',
        ];

        /* 插入队列 */
        /* 闭包序列化处理 */
        //$serializer = new Serializer();
        dispatch(new ExportData($header, '', '', $filename, $data->toArray()));
        return $this->getResponse('已加入导出队列', [], 200, url('admin/partner'));
    }


    /**
     * 查出员工列表
     *
     * @Author   qizhifei
     * @DateTime 2019-05-27
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function inviteList(Request $request)
    {
        $payload = $request->all();
        //关联模型查询
        $preData = User::with(['userDepartment', 'userPosition',])
            ->when((isset($payload['level']) && $payload['level'] != ''), function ($query) use ($payload) {
                $query->whereHas('userAccountInfo', function ($query) use ($payload) {
                    $query->Where('user_level_id', $payload['level']);
                });
            })
            ->where(['user_type' => 1])
            ->where(function ($query) use ($payload) {
                if (isset($payload['name']) && $payload['name'] != '') {
                    $query->Where('realname', 'like', "%$payload[name]%")
                        ->orWhere('number', 'like', "%$payload[name]%");
                }
                if (isset($payload['department']) && $payload['department'] != '') {
                    $query->Where(['department' => $payload['department']]);
                }
                if (isset($payload['position']) && $payload['position'] != '') {
                    $query->Where(['position' => $payload['position']]);
                }
                if (isset($payload['status']) && $payload['status'] != '') {
                    $query->Where(['status' => $payload['status']]);
                }
            })
            ->orderBy('id', 'desc')
            ->paginate($request->get('limit', 10));

        return Layui::tableJson($preData, 0, $preData->total());
    }


    /**
     * 更改邀请关系
     *
     * @Author   qizhifei
     * @DateTime 2019-05-27
     * @param    [type]     $id      [用户id]
     * @param    [type]     $invite_id      [邀请人id]
     * @param    Request $request [description]
     * @return   [type]              [description]
     */
    public function changeInvite($id, Request $request)
    {
        $inviteId = $request->input('invite_id');
        try {
            $thisData = UserInvite::where(['register_user_id' => $id])->first();
            //邀请人信息
            $inviteUser = User::findOrFail($inviteId);
            if(is_null($thisData) || !$thisData){
                //判断是否存在记录 没有则添加
                $thisData = new UserInvite;
                $thisData->inviter_code = $inviteUser->invite_code ?? '';
                $thisData->inviter_user_id = $inviteId;
                $thisData->inviter_realname = $inviteUser->realname ?? '';
                $thisData->inviter_phone = $inviteUser->phone ?? '';
                $thisData->register_user_id = $id;
            }else{
                $thisData->inviter_code = $inviteUser->invite_code ?? '';
                $thisData->inviter_user_id = $inviteUser->id;
                $thisData->inviter_realname = $inviteUser->realname ?? '';
                $thisData->inviter_phone = $inviteUser->phone ?? '';
            }
            $thisData->save();
            User::where(['id' => $id])->update(['inviter_user_id' => $inviteUser->id]);

        } catch (\Exception $exception) {
            dd($exception);
            throw new FormException('网络问题请稍后再试!');
        }
        return $this->getResponse('修改成功', [], 200);
    }


    /**
     * 查看充值记录
     *
     * @Author   qizhifei
     * @DateTime 2019-05-27
     * @param    [int]     $id [会员id]
     * @return   [json]         [列表]
     */
    public function moneyRecharge($id, Request $request)
    {
        $where['user_id'] = $id;

        $where['status'] = AccountLog::SUCCESS;
        $accountLog = AccountLog::where($where)
            ->where(function ($query) {
                $query->where('type','=',1);
                $query->orWhere('type','=',4);
            })

            ->orderBy('id', 'desc')
            ->paginate($request->get('limit', 5));
        return Layui::tableJson($accountLog, 0, $accountLog->total());
    }


    /**
     * 查看八贝币记录
     *
     * @Author   qizhifei
     * @DateTime 2019-05-27
     * @param    [int]     $id [会员id]
     * @return   [json]         [列表]
     */
    public function moneyEightConsh($id, Request $request)
    {
        $user = User::find($id);
        $page = $request->input('page');
        $coinList = $this->box_service->coinList($user->openid,$page);
        return Layui::tableJson($coinList['data'] ?? '', 0, $coinList['pageCount'] );
    }


    /**
     * 查看贝壳记录
     *
     * @Author   qizhifei
     * @DateTime 2019-05-27
     * @param    [int]     $id [会员id]
     * @return   [json]         [列表]
     */
    public function moneyConsh($id, Request $request)
    {
        $user = User::find($id);
        $page = $request->input('page');
        $coinList = $this->box_service->conshList($user->openid,$page);
        return Layui::tableJson($coinList['data'], 0, $coinList['pageCount'] );
    }


    /**
     * 查看关联订单信息
     *
     * @Author   qizhifei
     * @DateTime 2019-05-28
     * @param    [type]     $id [description]
     * @return   [type]         [description]
     */
    public function orderList($id, Request $request)
    {

        $preData = Order::with(['OrderGoods', 'User'])
            ->orderBy('updated_at', 'desc')
            ->when(isset($id), function ($query) use ($id) {
                $query->where('user_id', $id);
            })
            ->paginate($request->get('limit', 30));

        $data = $preData->map(function ($item) {
            $item->real_pay = round($item->real_pay,2);
            $item->pay_type_name = $item->pay_type ? Order::PAY_TYPE[$item->pay_type] : '';
            $item->status_name = Order::STSTUS[$item->status];
            $item->express_string = $item->order_type == Order::TYPE_ONLINE ? $item->express_name . '<br>' . $item->express_order : '不需要配送';
            if (isset($item->OrderGoods)) {
                $shop_string = '';
                foreach ($item->OrderGoods as $k => $v) {
                    $shop_string .= '<img src="' . $v->photo . '" alt="" width="30px" height="30px">' . $v->title . ' ✖️ ' . $v->amount;
                }
            }
            $item->shop_string = $shop_string;
            return $item;
        });

        return Layui::tableJson($data, 0, $preData->total());
    }

    /**
     * 会员等级页面
     *
     * @Author   qizhifei
     * @DateTime 2019-05-28
     * @return   [type]     [description]
     */
    public function levelSet(Request $request)
    {
        if ($request->isMethod('post')) {
            $payload = $request->all(['data1', 'data2', 'data3', 'data4', 'data5', 'data6', 'data7']);
            DB::beginTransaction();
            try {
                foreach ($payload as $value) {
                    $where['id'] = $value['id'];
                    $updata['money'] = $value['money'] ?? 0;
                    $updata['deadline'] = $value['deadline'] ?? 0;
                    $updata['discount'] = $value['discount'];
                    $updata['status'] = empty($value['status']) ? 2 : 1;
                    $updata['updated_at'] = date('Y-m-d H:i:s');
                    UserLevel::where($where)->update($updata);

                }
            } catch (\Exception $exception) {
                DB::rollBack();
                throw new FormException('网络问题请稍后再试!');
            }
            DB::commit();
            return $this->getResponse('修改成功', [], 200);
        } else {
            return view('Admin.user.levelset');
        }
    }

    /**
     * 获取会员等级列表
     *
     * @Author   qizhifei
     * @DateTime 2019-05-28
     * @return   [type]     [description]
     */
    public function levelSetTable(Request $request)
    {
        $data = UserLevel::all();
        return Layui::tableJson($data, 0, 0);
    }


    /**
     * 会员邀请查询
     *
     * @Author   qizhifei
     * @DateTime 2019-05-29
     * @param    [int]     $id [传入的id]
     * @return   [type]         [description]
     */
    public function userInvit($id = 0, Request $request)
    {
        //if($id != 0){
        if ($request->isMethod('post')) {
            $payload = $request->all();
            $sUser = User::where(function ($query) use ($payload) {
                if (isset($payload['name']) && $payload['name'] != '') {
                    $query->Where('realname', '=', $payload['name'])
                        ->orWhere('phone', '=', $payload['name']);
                }
            })
            ->first();

            if (!isset($payload['name']) || is_null($payload['name']) || $payload['name'] == '' || is_null($sUser)) {
                return Layui::tableJson('', 0, 0);
            }

            //关联模型查询
            $preData = User::with(['userAccountInfo'])
                ->where(['inviter_user_id' => $sUser->id, 'is_real'=>1])
                ->orderBy('id', 'desc')
                ->paginate($request->get('limit', 10));
            $data = $preData->map(function ($item) {
                $item->surplus_time = $this->surplusTime($item->userAccountInfo); //会员剩余时间
                $item->calcLevel = is_null($item->userAccountInfo) ? '' : $this->calcLevel($item->userAccountInfo); //会员等级
                $item->sex_name = is_null($item->sex) ? '' : ($item->sex == 1 ? '男' : '女'); //性别
                return $item;
            });

            return Layui::tableJson($preData, 0, $preData->total());
        } else {
            return view('Admin.user.userinvite');
        }
    }


    /**
     * 查看会员订单
     *
     * @Author   qizhifei
     * @DateTime 2019-06-01
     * @param    [type]     $id [description]
     * @return   [type]         [description]
     */
    public function orderLists($id)
    {

    }


}
